package com.hd.trans.ui.activity;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.common.Constants;
import com.hd.trans.common.interf.Callback;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.framework.click.XClickUtil;
import com.hd.trans.framework.dialog.ConfirmDialog;
import com.hd.trans.ui.adapter.RecordTextAdapter;
import com.hd.trans.ui.base.BaseActivity;
import com.hd.trans.utils.ToastUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * 收藏夹
 */
public class FavoritesManagerActivity extends BaseActivity implements View.OnClickListener {

    private ImageView back;
    private TextView title;
    private TextSwitcher rightText;
    private RecyclerView recycler;
    private FrameLayout flBottom;
    private TextView tvDeleteItems;

    private RecordTextAdapter adapter;
    private ConfirmDialog dialog;
    private ImageView icon;
    private String titleName;

    //open入口
    public static void open(Context context, String titleName) {
        Intent intent = new Intent(context, FavoritesManagerActivity.class);
        intent.putExtra("title_name",titleName==null?"收藏夹":titleName);
        context.startActivity(intent);
    }

    //open入口
    public static void open(Context context) {
        Intent intent = new Intent(context, FavoritesManagerActivity.class);
        intent.putExtra("title_name", "收藏夹");
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_favorites_manager;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        titleName = getIntent().getStringExtra("title_name");
        initView();
    }

    private void initView() {
        back = (ImageView) findViewById(R.id.back);
        title = (TextView) findViewById(R.id.tilte);
        rightText = (TextSwitcher) findViewById(R.id.right_text);
        rightText.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                TextView textView = new TextView(FavoritesManagerActivity.this);
                textView.setTextSize(18);
                textView.setGravity(Gravity.RIGHT);
                textView.setTextColor(getResources().getColor(R.color.primary_color));
                return textView;
            }
        });
        recycler = (RecyclerView) findViewById(R.id.recycler);
        icon = (ImageView) findViewById(R.id.icon);
        flBottom = (FrameLayout) findViewById(R.id.fl_bottom);
        tvDeleteItems = (TextView) findViewById(R.id.tv_delete_items);

        title.setText(TextUtils.isEmpty(titleName)?getResources().getString(R.string.favorites):titleName);
        rightText.setText(getResources().getString(R.string.history_exit_manager));
        tvDeleteItems.setText(String.format("移出%s", titleName));
        ((TextView)findViewById(R.id.tv_tips)).setText("暂无收藏");

        back.setOnClickListener(this);
        rightText.setOnClickListener(this);
        tvDeleteItems.setOnClickListener(this);

        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setItemAnimator(new DefaultItemAnimator());
        adapter = new RecordTextAdapter(null);
        adapter.setAnimationEnable(true);
        adapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom);
        recycler.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                if(adapter.isManagerType()){
                    view.findViewById(R.id.check_box).performClick();
                }else {
                    LiveEventBus.get(Constants.COLLECTION_SHOW).post(adapter.getData().get(position));
                    finish();
                }
            }

        });

        adapter.setCallbackListener(new Callback() {
            @Override
            public void onCallback() {
                if(adapter.getData().size() == adapter.getSelectedData().size()){
                    //全选状态
                    selectedAllStatus();
                }else {
                    //非全选状态
                    cancelSelectedAllStatus();
                }
            }
        });

        entryManagerStatus();
    }

    @Override
    protected void onResume() {
        refreshRecords();
        super.onResume();
    }

    /**
     * 刷新记录
     */
    private void refreshRecords() {
        Observable.create((ObservableOnSubscribe<List<TranslateRecord>>) emit -> {
            emit.onNext(DataBaseMgr.getInstance().getCollectedRecords());
            emit.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(new DisposableObserver<List<TranslateRecord>>() {
                    @Override
                    public void onNext(List<TranslateRecord> list) {
                        adapter.setNewInstance(list);
                        if(list == null || list.isEmpty()){
                            recycler.setVisibility(View.GONE);
                            rightText.setVisibility(View.GONE);
                        }else {
                            recycler.setVisibility(View.VISIBLE);
                            rightText.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    public void onClick(View v) {
        if (XClickUtil.isFastDoubleClick(v, XClickUtil.INTERVAL_MILLIS)) {
            return;
        }
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.right_text) {
            TextView currentTextView = (TextView) rightText.getCurrentView();
            String rightTextStr = currentTextView.getText().toString();
            if (rightTextStr.equals(getResources().getString(R.string.select_all))) {
                //全选
                adapter.selectAll(new Callback() {
                    @Override
                    public void onCallback() {
                        selectedAllStatus();
                    }
                });
            } else if (rightTextStr.equals(getResources().getString(R.string.cancel_select_all))) {
                //取消全选
                adapter.cancelSelectAll(new Callback() {
                    @Override
                    public void onCallback() {
                        cancelSelectedAllStatus();
                    }
                });

            }
        } else if (id == R.id.tv_delete_items) {
            //移出文本翻译记录/收藏夹
            if(adapter.getData().size() == 0 ){
                ToastUtils.showNormal("没有任何收藏记录");
                return;
            }
            if (dialog == null) {
                dialog = ConfirmDialog.builder()
                        .setContent(getResources().getString(R.string.confirm_tip2))
                        .rightTxtColor(TranslationInterior.getThemeColor())
                        .setRightListenner(new ConfirmDialog.OnComfrimDialogListenner() {
                            @Override
                            public void OnComfrim(Dialog dialog) {
                                List<TranslateRecord> records = adapter.getSelectedData();
                                DataBaseMgr.getInstance().deleteCollectRecords(records);

                                ToastUtils.showNormal("已移出" + titleName);
                                tvDeleteItems.setEnabled(false);
                                tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_cccccc_16);
                                adapter.getSelectedData().clear();
                                //refreshRecords();

                                finish();
                            }
                        })
                        .build();
            }
            dialog.show(getSupportFragmentManager(), "TextHistoryActivity");
        }
    }

    private void entryManagerStatus(){
        adapter.setShowType(true);
        back.setVisibility(View.VISIBLE);
        flBottom.setVisibility(View.VISIBLE);
        rightText.setText(getResources().getString(R.string.select_all));
    }

    private void selectedAllStatus(){
        //全选
        tvDeleteItems.setEnabled(true);
        tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_blue_16);
        rightText.setText(getResources().getString(R.string.cancel_select_all));
    }

    private void cancelSelectedAllStatus(){
        //取消全选
        rightText.setText(getResources().getString(R.string.select_all));
        if(adapter.getSelectedData().size() == 0){
            tvDeleteItems.setEnabled(false);
            tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_cccccc_16);
        }else {
            tvDeleteItems.setEnabled(true);
            tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_blue_16);
        }
    }

}